#!/usr/bin/env bun

import { prisma } from '../src/db'
import bcrypt from 'bcryptjs'

async function initializeAdmin() {
  console.log('🚀 Initializing admin account...')

  try {
    // 检查是否已存在管理员账户
    const existingAdmin = await prisma.user.findFirst({
      where: { role: 'ADMIN' }
    })

    if (existingAdmin) {
      console.log('✅ Admin account already exists:', existingAdmin.email)
      return
    }

    // 创建默认管理员账户
    const adminEmail = process.env.ADMIN_EMAIL || 'admin@orderSystem.com'
    const adminPassword = process.env.ADMIN_PASSWORD || 'admin123456'
    const adminUsername = process.env.ADMIN_USERNAME || 'admin'

    // 检查邮箱是否已被使用
    const existingUser = await prisma.user.findUnique({
      where: { email: adminEmail }
    })

    if (existingUser) {
      // 如果用户存在但不是管理员，升级为管理员
      if (existingUser.role !== 'ADMIN') {
        await prisma.user.update({
          where: { id: existingUser.id },
          data: { role: 'ADMIN' }
        })
        console.log('✅ Upgraded existing user to admin:', adminEmail)
      } else {
        console.log('✅ Admin account already exists:', adminEmail)
      }
      return
    }

    // 加密密码
    const hashedPassword = await bcrypt.hash(adminPassword, 12)

    // 创建管理员账户
    const admin = await prisma.user.create({
      data: {
        email: adminEmail,
        username: adminUsername,
        password: hashedPassword,
        role: 'ADMIN',
        isActive: true
      }
    })

    console.log('✅ Admin account created successfully!')
    console.log('📧 Email:', admin.email)
    console.log('👤 Username:', admin.username)
    console.log('🔑 Password:', adminPassword)
    console.log('')
    console.log('⚠️  Please change the default password after first login!')

    // 记录审计日志
    await prisma.auditLog.create({
      data: {
        userId: admin.id,
        action: 'ADMIN_INIT',
        resource: 'User',
        details: 'Initial admin account created'
      }
    })

  } catch (error) {
    console.error('❌ Failed to initialize admin account:', error)
    process.exit(1)
  } finally {
    await prisma.$disconnect()
  }
}

// 运行初始化
initializeAdmin().catch((error) => {
  console.error('❌ Initialization failed:', error)
  process.exit(1)
})
